package com.zjitc.service.impl;


import com.zjitc.entity.LoginUser;
import com.zjitc.entity.User;
import com.zjitc.mapper.AuthMapper;
import com.zjitc.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * UserDetailsService接口实现类
 * 用于Spring Security从数据库中加载用户信息
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthMapper authMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        User user = userMapper.getUserByName(username);

        // 如果没有查询到用户，抛出异常
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        
        // 获取权限信息
        List<String> permissions = authMapper.getPermsByUserId(user.getId());
        // 返回UserDetails实现类
        return new LoginUser(user, permissions);
    }
} 